package com.luwak.controller.sys;

import com.luwak.common.base.R;
import com.luwak.common.utils.JWTUtils;
import com.luwak.modules.sys.entity.SysUserEntity;
import com.luwak.modules.sys.form.SysLoginForm;
import com.luwak.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ChenXc
 * @version V1.0
 * @Date 2018/3/26  9:31
 * @Description TODO(登录)
 */
@Api(value = "系统controller", description = "登录{\"username\":\"admin\",\"password\":\"admin\"}", tags = {"登录接口"})
@RestController
public class SysLoginController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录
     *
     * @param sysLoginForm
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/sys/login")
    public R Login(@RequestBody @ApiParam(name = "账号密码", value = "传入json格式", required = true) SysLoginForm sysLoginForm) {

        SysUserEntity userEntity = sysUserService.queryByUserName(sysLoginForm.getUsername());

        //账户不存在或、密码错误
        if (userEntity == null || !userEntity.getPassword().equals(
                new Sha256Hash(sysLoginForm.getPassword(), userEntity.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        if (userEntity.getLocked() == 1) {
            return R.error("账号已被锁定,请联系管理员");
        }

        String token = JWTUtils.sign(sysLoginForm.getUsername(), sysLoginForm.getPassword());

        return R.ok("登录成功").put("data", token);
    }

}
